package org.gdgbologna.devfest;

import org.gdgbologna.devfest.adapter.TalkAdapter;
import org.gdgbologna.resources.Devfest;
import org.gdgbologna.resources.Session;
import org.gdgbologna.resources.Talk;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;

public class AllListFragment extends Fragment {
	
	public static final String INDEX_OF_DEVFEST = "index_devfest";
	
	LinearLayout layout;
	ListView list;
	TalkAdapter adapter;
	MainActivity	act;
	Devfest devfest;
		
	public static AllListFragment newInstance(Devfest devfest){
		AllListFragment f = new AllListFragment();
		
		Bundle args = new Bundle();
		args.putParcelable("devfest", devfest);
		f.setArguments(args);
		
		return f;
	}
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View V = inflater.inflate(R.layout.allfragment, container, false);
        layout = (LinearLayout) V.findViewById(R.id.all_container);
        list = (ListView) V.findViewById(R.id.list);
        
        act = (MainActivity) getActivity();
		
		adapter = new TalkAdapter(act);
        list.setAdapter(adapter);
        
        list.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
				// TODO Auto-generated method stub
				Talk t = (Talk)adapter.getItem(arg2);
				act.showDetail(t);
			}
        });

        devfest = (Devfest) getArguments().getParcelable("devfest");
        if (savedInstanceState != null) {
        	devfest = (Devfest) savedInstanceState.getParcelable("devfest");        	
        }
        loadList();
        
        return V;
    }
	
	public void loadList(){
		if (adapter!=null) adapter.clear();

		for (int i=0; i<devfest.session.size(); i++){
        	Session e = devfest.session.get(i);
        	adapter.addSeparatorItem(e);
        
        	for (int k=0; k< e.talks.size(); k++){
        		adapter.addItem(e.talks.get(k));
        	}
        }
        
        adapter.notifyDataSetChanged();
        list.setSelection(0);
	}
	
	@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable("devfest", devfest);
    }

	public void changeList(Devfest _fest) {
		devfest = _fest;
		loadList();
	}
	
}
